package br.com.sgi.autentication;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import br.com.sgi.model.Users;

@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	@PersistenceContext
	  private EntityManager entityManager;

	  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	    return findByUsername(username);
	  }
	  
	  private Users findByUsername(String username) {
	    try{
	      return entityManager.createNamedQuery("findByUsername", Users.class).setParameter("username", username).getSingleResult();
	    	
	    	
	      
	      
	    }catch (NoResultException e) {
	      throw new UsernameNotFoundException("Usuario nao encontrado");
	    }
	  }
}

